package net.e4net.watrix.example.base.factory;

import java.util.Hashtable;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import net.e4net.watrix.common.tao.TaoConnection;
import net.e4net.watrix.common.tao.TaoConnectionFactory;
import net.e4net.watrix.common.tao.TaoException;
import net.e4net.watrix.common.tao.simpleDao.SimpleDaoConnection;
import net.e4net.watrix.example.common.ExamProperties;

public class ExamSimpleDaoConnectionFactory extends TaoConnectionFactory {

    protected static DataSource dataSource = null;
    protected static Object lock = new Object();

    public TaoConnection getConnection(Properties arg0) throws TaoException {

        ExamProperties examProp = ExamProperties.getInstance();
        String poolname = examProp.getProperty("JNDI_DBPOOL_NAME");
        String factory  = examProp.getProperty("INITIAL_CONTEXT_FACTORY");
        try {
            if ( dataSource==null ) {
                Context ctx = null;
                if ( factory.length()>0 ) {
                    Hashtable ht = new Hashtable();
                    ht.put(Context.INITIAL_CONTEXT_FACTORY,  factory);
                    ctx = new InitialContext(ht);
                } else {
                    ctx = new InitialContext();
                }
                DataSource ds = (DataSource) ctx.lookup(poolname);
                synchronized (lock) {
                    dataSource = ds;
                }
            }

            return SimpleDaoConnection.getInstance( dataSource.getConnection() );

        } catch( Throwable t) {
            throw new TaoException( ExamProperties.getMessage("dbConnectionFailed") ,t);
        }
    }

}